<template>
  <!-- 搜索 -->
  <div class="my-wbox">
    <MyForm :formData="formData" @listenClick="listenClick" :isSetForm="isSetForm"></MyForm>
  </div>
</template>
<script setup lang='ts'>
import { ref, reactive, getCurrentInstance, computed } from 'vue'
import MyForm from '@/components/MyForm.vue'
import { ParentForm } from '@/interface/index'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { addUserApi, editUserApi, getAreaListApi, userDetailApi } from '@/views/account/api/accountApi'
import { useStore } from '@/store'
import { SelectObj} from '@/interface/index'
import { AddUserParams, EditUserParams } from '@/views/account/interface/interface'
const store = useStore()
const route = useRoute()
const router = useRouter()
const routeId = route.query.id ?? '' //编辑传过来的id 新增没有
//监听加载
const loading = computed(() => {
  return store.getters['loading/getLoad']
})
//触发表单是否重新赋值 编辑表单的时候用
const isSetForm = ref<boolean>(false)
//封装的表单
const formData = reactive<ParentForm>({
  formItem: [
    { key: 'userName', styleType: 'input', label: '姓名', value: '', placeholder: '请输入姓名' },
    { key: 'userLogin', styleType: 'input', label: '手机号码', value: '', placeholder: '请输入手机号码', type: 'number' },
    { key: 'roleId', styleType: 'radio', label: '角色', value: '', placeholder: '请选择', data: [{ label: '管理员', value: 2 }, { label: '督察员', value: 3 }] },
    { key: 'roleAuth', styleType: 'select', label: '督察的乡镇', value: [], placeholder: '请选择', data: [], type: 'multiple', hide(row: any): boolean { return row.roleId == 3 }, },
    { key: 'funcAuth', styleType: 'checkbox', label: '功能权限', value: [], placeholder: '请选择', data: [{ label: '账号管理权限', value: '1' }, { label: '常驻人员数据查询权限', value: '2' }, { label: '来返人员数据统计权限', value: '3' },{ label: '数据统计权限', value: '4' }] },
  ],
  rules: {
    userName: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 2, max: 10, message: '请输入2-10长度用户名', trigger: 'blur' },
    ],
    userLogin: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
      { min: 11, max: 11, message: '请输入11长度手机号码', trigger: 'blur' },
    ],
    roleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
    roleAuth: [{ required: true, message: '请选择需要督察的乡镇', trigger: 'change' }],
    funcAuth: [{ required: true, message: '请选择功能权限', trigger: 'change' }],
  },
  btn: [
    { name: 'mySure', text: '确定', type: 'primary' },
    { name: 'myCancel', text: '取消' },
  ],
  size: 'large',//'large' | 'default' | 'small'
})
//提交
const listenMySubmit = async (formData: any) => {
  let obj = JSON.stringify(formData)
  let val = JSON.parse(obj)
  val.roleAuth =  val.roleId==3?val.roleAuth.join(','):''
  val.funcAuth = val.funcAuth.join(',')
  let params = val
  if (routeId) {
    //编辑
    params.userId=routeId
    onEdit(params)
  } else {
    onAdd(params)
  }
}
//定义方法对象 注意定义的方法 必须在上面已经申明 所以建议objFun申明和 listenClick方法 写在页面最下面
const objFun = { 'listenMySubmit': listenMySubmit }
// 监听子级表格  传过来的方法禁用
const listenClick = (name: string, val: any) => {
  objFun[name](val)
}
//api
//新增提交接口any 写成对应的接口
const onAdd = async (params: AddUserParams) => {
  try {
    let res = await addUserApi(params)
    if (res?.code === 0) {
      router.go(-1)
      ElMessage({ type: 'success', message: '新增成功' })
    }
    store.commit('loading/setLoad', false)
  } catch {
    store.commit('loading/setLoad', false)
  }
}
//编辑提交接口any 写成对应的接口
const onEdit = async (params: EditUserParams) => {
  try {
    let res = await editUserApi(params)
    if (res?.code === 0) {
      router.go(-1)
      ElMessage({ type: 'success', message: '编辑成功' })
    }
    store.commit('loading/setLoad', false)
  } catch {
    store.commit('loading/setLoad', false)
  }
}
//获取所有乡镇 
const onAreaList = async () => {
  try {
    let params = { id: '0' }
    let res = await getAreaListApi(params)
    if (res?.code === 0) {
      let arr: SelectObj[] = []
      res.data.forEach(t => {
        arr.push({ label: t.name, value: t.areaCode })
      })
      formData.formItem[3].data = arr
    }
    store.commit('loading/setLoad', false)
  } catch {
    store.commit('loading/setLoad', false)
  }
}
//查详情 用户信息
const onUserDetail = async () => {
  try {
    let params = { id: routeId as string }
    let res = await userDetailApi(params)
    if (res?.code === 0) {
      formData.formItem.forEach(t => {
        let formObj = res.data
        if (t.key === 'roleAuth' || t.key === 'funcAuth') {
          t.value = formObj[t.key] ? formObj[t.key].split(',') : []
        } else {
          t.value = formObj[t.key] ? formObj[t.key] : ''
        }
      })
      isSetForm.value = !isSetForm.value
    }
    store.commit('loading/setLoad', false)
  } catch {
    store.commit('loading/setLoad', false)
  }
}
onAreaList()//获取所有乡镇 
if (routeId) {//编辑的时候获取用户详情
  onUserDetail()
}
</script>
<style scoped lang='scss'>
</style>